<template>
    <div>
        <el-row>
            <el-col :span="5">
                <div class="tree">
                    <el-input placeholder="输入关键字进行过滤" v-model="filterText">
                    </el-input>
                    <el-tree @node-click="handlerClick" class="filter-tree" :data="EngData" :props="defaultProps"
                        :filter-node-method="filterNode" ref="tree">
                    </el-tree>
                </div>
            </el-col>
            <el-col :span="19">
                <!-- 折线图容器，修正ID并调整高度 -->
                <div id="line-chart" style="height: 400px;"></div>
                
                <div v-if="params.device_id" class="table">
                    <!-- 这里可以添加表格内容 -->
                </div>
                <div v-else style="line-height: 50px;color: red;font-size: 20px;text-align: center;">请点击设备查看数据</div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import { get } from '@/utils/request'
import { Line } from '@antv/g2plot'; // 引入折线图组件
export default {
    data() {
        return {
            filterText: '',
            defaultProps: { children: 'children', label: 'name' },
            monitorData: [],
            form: { time: [] },
            EngData: [],
            params: {
                page: 1,
                pageSize: 10,
                device_id: 0,
                engineer_id: 0,
            },
            total: 0,
            lineChart: null, // 存储折线图实例，用于销毁旧图表
        };
    },
    watch: {
        filterText(val) {
            this.$refs.tree.filter(val);
        },
    },
    methods: {
        // 初始化折线图（整合示例配置，适配多指标数据）
        initLineChart(data) {
            // 销毁旧图表（避免重复渲染）
            if (this.lineChart) {
                this.lineChart.destroy();
            }
            
            // 构造折线图数据：保留完整时间格式，转换为多系列格式
            const seriesData = [];
            data.forEach((item) => {
                // 每个指标生成一条数据
                seriesData.push({ time: this.fmtDate(item.insert_time), metric: 'tsp', value: item.tsp });
                seriesData.push({ time: this.fmtDate(item.insert_time), metric: 'pm10', value: item.pm10 });
                seriesData.push({ time: this.fmtDate(item.insert_time), metric: 'pm2.5', value: item.pm25 });
                seriesData.push({ time: this.fmtDate(item.insert_time), metric: '温度', value: item.temperature });
                seriesData.push({ time: this.fmtDate(item.insert_time), metric: '湿度', value: item.humidity });
            });
            
            // 渲染折线图（复用示例配置）
            this.lineChart = new Line('line-chart', {
                data: seriesData,
                xField: 'time',
                yField: 'value',
                seriesField: 'metric',
                label: {},
                point: {
                    size: 5,
                    shape: 'diamond',
                    style: {
                        fill: 'white',
                        stroke: '#5B8FF9',
                        lineWidth: 2,
                    },
                },
                tooltip: { showMarkers: false },
                state: {
                    active: {
                        style: {
                            shadowBlur: 4,
                            stroke: '#000',
                            fill: 'red',
                        },
                    },
                },
                interactions: [{ type: 'marker-active' }],
                xAxis: {
                    label: {
                        autoHide: true,
                        autoRotate: true,
                        rotate: 45, // 增加旋转角度，避免标签重叠
                    },
                },
                legend: {
                    position: 'top',
                },
                // 添加网格线，增强可读性
                grid: {
                    x: { visible: true },
                    y: { visible: true },
                },
            });
            this.lineChart.render();
        },
        // 日期格式化 - 保留完整的年月日时分
        fmtDate(time) {
            if (!time) return '';
            const date = new Date(time);
            return `${date.getFullYear()}-${(date.getMonth() + 1)
                .toString()
                .padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date
                    .getHours()
                    .toString()
                    .padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
        },
        // 树形节点点击
        async handlerClick(val, node) {
            if (!val.children) {
                this.params.device_id = val.id;
                this.params.engineer_id = val.engineer_id;
                this.params.page = 1;
                await this.getMonitor();
            }
        },
        // 请求监测数据
        async getMonitor() {
            let temp = { ...this.params };
            if (this.form.time) {
                temp.begin_time = this.form.time[0];
                temp.end_time = this.form.time[1];
            }
            try {
                let res = await get('/monitor/pageQuery', temp);
                this.monitorData = res.data.list || [];
                this.total = res.data.total || 0;
                
                // 数据不为空时，渲染折线图
                if (this.monitorData.length > 0) {
                    this.initLineChart(this.monitorData);
                } else {
                    // 清空图表
                    if (this.lineChart) {
                        this.lineChart.destroy();
                        this.lineChart = null;
                    }
                }
            } catch (error) {
                console.error('获取监测数据失败:', error);
            }
        },
        // 请求工程设备树
        async getEngDevData() {
            try {
                let res = await get('/engineer/findEngineerDeviceTree');
                this.EngData = res.data || [];
            } catch (error) {
                console.error('获取设备树失败:', error);
                this.EngData = [];
            }
        },
        // 树形节点过滤
        filterNode(value, data) {
            if (!value) return true;
            return data.name && data.name.indexOf(value) !== -1;
        },
        // 表格行样式
        tableRowClassName({ row, rowIndex }) {
            if (rowIndex % 2 === 0 || rowIndex === 0) {
                return 'warning-row';
            } else {
                return 'success-row';
            }
        },
    },
    created() {
        this.getEngDevData();
        // 初始不加载数据，等待用户选择设备
        // this.getMonitor();
    },
};
</script>
<style lang="scss" scoped>
.tree {
    height: calc(100vh - 60px);
    padding-right: 10px;
    border-right: 1px solid #ececec;
    margin-right: 10px;
}

::v-deep .el-table .warning-row {
    background: oldlace;
}

::v-deep .el-table .success-row {
    background: #f0f9eb;
}

// 为图表容器添加边框和内边距，美化显示
::v-deep #line-chart {
    margin: 10px 0;
    padding: 10px;
    border: 1px solid #eee;
    border-radius: 4px;
}
</style>